package com.future.dao;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.future.model.po.UserModel;
import com.future.model.vo.TownsServicesVO;

public class TownsDao extends BaseDAO<TownsServicesVO> {
	private static Logger logger = LogManager.getLogger(TownsDao.class);

	public TownsDao() {

	}

	public TownsDao(Connection conn) {
		super(conn);
	}

	public List<TownsServicesVO> findServicesByUserId(UserModel userModel) {
		List<TownsServicesVO> tsvos = new ArrayList<TownsServicesVO>();
		StringBuffer sb = new StringBuffer();
		sb.append(" select s.id servicesid,s.services,sa.answer,sa.id,sa.userid from services   ").append(
				" s left join services_answer sa on s.id=sa.servicesid  ");
		if (userModel != null && userModel.getId() != null && userModel.getId() > 0) {
			sb.append(" and  sa.userid=?");
			logger.info("判断sql=" + sb);
			tsvos = this.searchAsBeanList(sb.toString(), TownsServicesVO.class, userModel.getId());
		}
		return tsvos;
	}

	/**
	 * 修改第三部分判断题
	 * 
	 * @return
	 */
	public boolean updateServicesById(List<TownsServicesVO> servicesVOs) {
		boolean flag = false;
		String sql = " update services_answer set answer=? where servicesid=? and userid=? ";
		for (TownsServicesVO townsServicesVO : servicesVOs) {
			flag = this.update(sql, townsServicesVO.getAnswer(), townsServicesVO.getServicesid(),
					townsServicesVO.getUserid());
			if (!flag) {
				break;
			}
		}
		return flag;
	}

	/**
	 * 判断第三部分的判断题是否做过，如果做过返回true , 没做过返回 true
	 * 
	 * @param townsServicesVO
	 * @return
	 */
	public boolean isOrExist(TownsServicesVO townsServicesVO) {
		String sql = "select * from services_answer where userid=?";
		logger.info("判断第三部分的题是否做过sql=" + sql);
		List<TownsServicesVO> list = this.searchAsBeanList(sql, TownsServicesVO.class, townsServicesVO.getUserid());
		if (list != null && list.size() > 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 当前用户第一次做第三部分判断题
	 * 
	 * @param servicesVOs
	 * @return
	 */
	public boolean saveServicesAnswer(List<TownsServicesVO> servicesVOs) {
		boolean flag = false;
		String sql = "insert into services_answer(answer,userid,servicesid)values(?,?,?)";
		logger.info("sql=" + sql);
		for (TownsServicesVO townsServicesVO : servicesVOs) {
			flag = this.update(sql, townsServicesVO.getAnswer(), townsServicesVO.getUserid(),
					townsServicesVO.getServicesid());
			if (!flag)
				break;
		}
		return flag;
	}
}
